package org.client.iot.ui.project;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lucky.base.network.NetworkApi;
import com.lucky.base.network.observer.BaseObserver;
import com.lucky.utils.log.LogUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;

import org.client.iot.R;
import org.client.iot.databinding.ActivityProjectOptionBinding;
import org.client.iot.domain.DeviceInfoDto;
import org.client.iot.domain.MenuItem;
import org.client.iot.http.ApiService;
import org.client.iot.http.BaseDevReq;
import org.client.iot.ui.device.DeviceOptionActivity;
import org.client.iot.ui.device.EquipmentInspectionActivity;
import org.client.iot.ui.device.MechanicalResetActivity;
import org.client.iot.ui.device.ProductionTestActivity;
import org.client.iot.ui.project.adapter.ProjectOptionAdapter;
import org.tzw.template.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;

public class ProjectOptionActivity extends BaseActivity<ActivityProjectOptionBinding> {
    private MiniLoadingDialog mMiniLoadingDialog;
    private String[] projectOptionMenu;
    private ProjectOptionAdapter projectOptionAdapter;
    private String devName;
    private boolean isChargingStatus = false;

    @Override
    protected void initData() {
        projectOptionMenu = getResources().getStringArray(R.array.project_option_menu);
        projectOptionAdapter = new ProjectOptionAdapter(this, getMenuList());
        devName = getIntent().getStringExtra("devName");
    }

    private List<MenuItem> getMenuList() {
        List<MenuItem> menuList = new ArrayList<>();
        menuList.add(new MenuItem(projectOptionMenu[0], R.drawable.ico_dev_manager_dev_debug));
//        menuList.add(new MenuItem(projectOptionMenu[1], R.mipmap.ico_measure_data));
//        menuList.add(new MenuItem(projectOptionMenu[2], R.mipmap.ico_measure_point));
//        menuList.add(new MenuItem(projectOptionMenu[3], R.mipmap.ico_every_write));
//        menuList.add(new MenuItem(projectOptionMenu[4], R.mipmap.ico_maintenance_records));
        menuList.add(new MenuItem(projectOptionMenu[1], R.drawable.ico_dev_check));
        menuList.add(new MenuItem(projectOptionMenu[2], R.drawable.ico_mechanical_reset));
        menuList.add(new MenuItem(projectOptionMenu[3], R.drawable.debug_ico_start_charg));
        menuList.add(new MenuItem(projectOptionMenu[4], R.drawable.debug_ico_test));
        return menuList;
    }

    @Override
    protected void initView() {
        setSupportActionBar(mRoot.toolbarProjectOption);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//添加默认的返回图标
//        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        mRoot.textViewTitle.setText(devName);
        int spanCount = 3; // 3列
        int spacing = 30; // 每个item之间的间距(px)
        boolean includeEdge = true; // 是否在边缘也添加分割线
        mRoot.recOptionMenu.setLayoutManager(new GridLayoutManager(this, spanCount));
        mRoot.recOptionMenu.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));

        mRoot.recOptionMenu.setAdapter(projectOptionAdapter);
        updateBrakeMenuItem();
        getDevInfo();
    }

    @Override
    protected void initListener() {
        projectOptionAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (position) {
                case 0:
                    Intent intent = new Intent(this, DeviceOptionActivity.class);
                    intent.putExtra("devName", devName);
                    startActivity(intent);
                    break;
//                case 1:
//                    redirectToActivity(MonitorDataActivity.class);
//                    break;
//                case 2:redirectToActivity(MeasurePointActivity.class);break;
//                case 3:redirectToActivity(DailyRegistrationActivity.class);break;
//                case 4:redirectToActivity(MaintenanceRecordActivity.class);break;
                case 1:
                    redirectToActivity(EquipmentInspectionActivity.class);
                    break;
                case 2:
                    redirectToActivity(MechanicalResetActivity.class);
                    break;
                case 3:
                    charging();
                    break;
                case 4:
                    redirectToActivity(ProductionTestActivity.class);
                    break;
            }

        });
        mRoot.menuImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void updateBrakeMenuItem() {
        List<MenuItem> menuList = getMenuList();
        if (isChargingStatus) {
            menuList.set(3, new MenuItem("暂未充电", R.drawable.debug_ico_start_charg));
        } else {
            menuList.set(3, new MenuItem("充电中", R.drawable.debug_ico_start_charg_t));
        }
        projectOptionAdapter.setList(menuList);
        projectOptionAdapter.notifyDataSetChanged();
    }

    // 获取设备信息
    private void getDevInfo() {
        Observable<BaseDevReq<DeviceInfoDto>> compose = NetworkApi.createService(ApiService.class, "dev")
                .getDevInfo().compose(NetworkApi.applySchedulers(new BaseObserver<BaseDevReq<DeviceInfoDto>>() {
                    @SuppressLint({"CheckResult", "SetTextI18n"})
                    @Override
                    public void onSuccess(BaseDevReq<DeviceInfoDto> req) {
                        if (req == null) {
                            return;
                        }
                        runOnUiThread(() -> {
                            disLoading();
                            LogUtils.i("获取设备信息(获取设备充电状态)req==", req.toString());
                            if (req.getData() != null) {
                                if ("停止充电".equals(req.getData().getDeviceChargingStatus())) {
                                    isChargingStatus = true;
                                    updateBrakeMenuItem();
                                } else if ("刹车".equals(req.getData().getDeviceChargingStatus())) {
                                    isChargingStatus = false;
                                    updateBrakeMenuItem();
                                }
                            }
                        });
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onFailure(Throwable e) {
                        runOnUiThread(() -> {
                                    disLoading();
                                    showToastLong(e.getMessage());
                                }
                        );
                    }

                }));
    }


    private void disLoading() {
        runOnUiThread(() -> {
            if (mMiniLoadingDialog != null) {
                mMiniLoadingDialog.dismiss();
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        disLoading();
    }

    /**
     * 是否充电处理
     */
    private void charging() {

    }

    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount; // 列数
        private int spacing; // 分割线宽度（px）
        private boolean includeEdge; // 是否在边缘也添加分割线

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item的位置
            int column = position % spanCount; // 计算列号

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // 计算左边距
                outRect.right = (column + 1) * spacing / spanCount; // 计算右边距

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item底部边距
            } else {
                outRect.left = column * spacing / spanCount; // 计算左边距
                outRect.right = spacing - (column + 1) * spacing / spanCount; // 计算右边距
                if (position >= spanCount) {
                    outRect.top = spacing; // item顶部边距（除了第一行）
                }
            }
        }
    }


}